<template>
  <div class="main">
    <!-- <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit"> -->

    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <van-field
          v-model="model.username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="model.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <br />
      <van-row :gutter="24" style="margin: 0 16px;">
        <van-col span="12">
          <van-field
            v-model="model.inputCode"
            placeholder="验证码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-col>
        <van-col span="12" >
          <img v-if="requestCodeSuccess" style="height: 44px;" :src="randCodeImage" @click="handleChangeCheckCode" />
          <img v-else style="height: 44px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode" />
        </van-col>
      </van-row>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>

    <!-- <a-form-item style="margin-top:24px">
        <a-button size="large"  type="primary"  htmlType="submit"  class="login-button"  :loading="loginBtn"  @click.stop.prevent="handleSubmit" :disabled="loginBtn">确定
        </a-button>
      </a-form-item> -->

    <!-- </a-form-model> -->
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, ENCRYPTED_STRING } from '@/store/mutation-types'
import { encryption, getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix } from '@/utils/util'
import { getAction } from '@/api/manage'

import { mapActions } from 'vuex'
import md5 from 'md5'
import { Notify } from 'vant';

export default {
  components: {},
  data() {
    return {
      model: {
        username: '',
        password: '',
        inputCode: '',
      },
      requestCodeSuccess: false,
      randCodeImage: '',
      currdatetime: '',

      rememberMe: true,
      loginBtn: false,
      encryptedString: {
        key: '',
        iv: '',
      },
    }
  },
  created() {
    console.log('jinru')
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.rememberMe = true
    this.handleChangeCheckCode()

    const sessionid = this.getCookie('sessionid')
    console.log(sessionid);
    if(sessionid != null && sessionid != ''){
      this.model.username = sessionid
      this.model.password = sessionid
      this.model.inputCode = "zwtLogin"
      this.handleSubmit()
    }

    const qwtoken = this.getQueryString('token')
    console.log(qwtoken);
    if(qwtoken != null && qwtoken != ''){
      this.model.username = qwtoken
      this.model.password = qwtoken
      this.model.inputCode = "qwLogin"
      this.handleSubmit()
    }

  },
  methods: {
    ...mapActions(['Login']),
    /**刷新验证码*/
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime()
      this.model.inputCode = ''
      getAction(`/sys/randomImage/${this.currdatetime}`)
        .then((res) => {
          if (res.success) {
            this.randCodeImage = res.result
            this.requestCodeSuccess = true
          } else {
            this.$message.error(res.message)
            this.requestCodeSuccess = false
          }
        })
        .catch(() => {
          this.requestCodeSuccess = false
        })
    },
    getQueryString (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    	var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
    	var r = window.location.search.substring(1).match(reg);
    	var q = window.location.pathname.substring(1).match(reg_rewrite);
    	if(r != null){
    		return r[2];
    	}else if(q != null){
    		return q[2];
    	}else{
    		return null;
    	}
    },
    getCookie(name) {
      let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      if (arr = document.cookie.match(reg))
        return arr[2];
      else
         return null;
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.acceptUsername(temp)
        }
      })
    },

    acceptUsername(username) {
      this.model['username'] = username
    },

    //登录
    handleSubmit() {
      this.loginBtn = true
      let loginParams = {
        username: this.model.username,
        password: md5(this.model.password),
        captcha: this.model.inputCode,
        checkKey: this.currdatetime,
        remember_me: this.rememberMe,
      }
      localStorage.clear()
      sessionStorage.clear()
      console.log('登录参数', loginParams)
      this.Login(loginParams)
        .then((res) => {
          console.log('221111', res)
          this.requestSuccess(res.result)
        })
        .catch((err) => {
          this.requestFailed(err)
        })
    },
    // 校验失败
    validateFail() {
      this.loginBtn = false
    },
    // 登录后台成功
    requestSuccess(loginResult) {
      // let user = Vue.ls.get(USER_INFO)
      // this.username = user.username
      // let ids = user.relTenantIds

      this.$store.dispatch('saveTenant', '')
      this.loginSuccess()
    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'

      this.$notify({ type: 'error', message: description })
      //账户密码登录错误后更新验证码
      this.handleChangeCheckCode()
      this.loginBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      // const isJump = localStorage.getItem('$showGridArrow') === 'true'
      // if (isJump) return
      this.$router.push({ path: '/' }).catch(() => {
        console.log('登录跳转首页出错')
      })
      this.$notify({ type: 'success', message: `${timeFix()}，欢迎回来` })
    },

    //获取密码加密规则
    getEncrypte() {
      var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
      if (encryptedString == null) {
        getEncryptedString().then((data) => {
          this.encryptedString = data
        })
      } else {
        this.encryptedString = encryptedString
      }
    },
  },
}
</script>
<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>